package com.yabiao.idempotent.token;

import com.yabiao.idempotent.exception.IdempotentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * <p>
 *
 * </p>
 *
 * @author: zhangyb
 * @create: 2020-09-13
 **/
@Component
public class TokenService {
    @Autowired
    private RedisService redisService;

    public String createToken(){
        String token = UUID.randomUUID().toString();
        redisService.setEx(token,token,1000L);
        return token;
    }
    public boolean checkToken(HttpServletRequest request) throws IdempotentException {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
            if (StringUtils.isEmpty(token)){
                throw new IdempotentException("不允许访问");
            }
        }
        if (!redisService.exists(token)){
            throw new IdempotentException("无权限访问");
        }
        boolean remove = redisService.remove(token);
        if (!remove){
            throw new IdempotentException("重复的操作");
        }
        return true;
    }
}
